package com.aipp.mall.common.redis;

import com.aipp.mall.common.model.LoginMember;
import com.aipp.mall.common.utils.Constants;
import com.aipp.mall.h5.domain.entity.Member;
import com.aipp.mall.h5.mapper.MemberMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Slf4j
@Component
public class TokenService {

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Resource
    private RedisCache redisCache;

    @Resource
    private MemberMapper memberMapper;


    public Member getMember(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StrUtil.isNotEmpty(token)) {
            try {
                LoginMember loginMember = redisCache.getCacheObject(getTokenKey(token));
                verifyMemberToken(loginMember);
                return redisCache.getCacheObject(getMemberKey(token));
            } catch (Exception e) {
                log.error("",e);
            }
        }
        return null;
    }

    /**
     * 获取请求token
     *
     * @param request 请求
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    public void refreshMemberToken(LoginMember loginMember) {
        loginMember.setLoginTime(System.currentTimeMillis());
        loginMember.setExpireTime(loginMember.getLoginTime() + 30 * 24 * 60 * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        redisCache.setCacheObject(getTokenKey(loginMember.getToken()), loginMember, 30, TimeUnit.DAYS);
        Member member = memberMapper.selectById(loginMember.getMemberId());
        redisCache.setCacheObject(getMemberKey(loginMember.getToken()), member, 30, TimeUnit.DAYS);
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }

    private String getMemberKey(String token) {
        return Constants.LOGIN_MEMBER_TOKEN_KEY + token;
    }

    public String createMemberToken(LoginMember loginMember) {
        String token = IdUtil.fastSimpleUUID();
        loginMember.setToken(token);
        refreshMemberToken(loginMember);
        return token;
    }

    public void verifyMemberToken(LoginMember loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshMemberToken(loginUser);
        }
    }
}
